/**
 * Created by Edwin on 2015/12/16 0016.
 */

var url = require('url');
var path = require('path');
var fs = require('fs');
//加密类
var crypto = require("crypto");
var mongoose = require('mongoose');
var shortid = require('shortid');
var Setmeal = require("../Setmeal");
var Purchase = require("../Purchase");
var Sale = require("../Sale");
var CashFlow=require("../CashFlow");
var Ingredient=require('../Ingredient');

var rootPath = path.resolve(__dirname + '/..')
//站点配置
var settings = require("./settings");
var db = mongoose.connect('mongodb://'+settings.URL+":"+settings.PORT+"/"+settings.DB);
//mongoose.connect('mongodb://'+settings.USERNAME+':'+settings.PASSWORD+'@'+settings.HOST+':'+settings.PORT+'/'+settings.DB+'');

//扫描数据模块
var modelMap={};
var scanModel=function(){
    files = fs.readdirSync(rootPath);//需要用到同步读取
    files.forEach(function(file){
        if(file!="db") {
            var modelName = file.slice(0, file.indexOf("."));
            modelMap[modelName] = require(path.join(rootPath, "/" + modelName));
        }
    });
    console.log("数据模型加载完成!");
}
scanModel();

var DbCore = {
    wrapData:function(obj,reCode){
        var res={};
        res["reCode"]=reCode;
        res["data"]=obj;
        res["date"]=new Date();
        console.log(res);
        return res;
    },
    //信息删除操作
    del : function(key,req,res,logMsg){
        var params = url.parse(req.url,true);
        var targetId = params.query.uid;
        if(shortid.isValid(targetId)){
            modelMap[key].remove({_id : params.query.uid},function(err,result){
                if(err){
                    res.end(err);
                }else{
                    console.log(logMsg+" success!");
                    res.end("success");
                }
            })
        }else{
            res.end(settings.system_illegal_param);
        }

    },
    findAll : function(key,res,callback){//查找指定对象所有记录
        modelMap[key].find({}, function (err,result) {
            console.log("模型【"+key+"】【findAll】获取"+(err?"失败":"成功"));
            res.json(DbCore.wrapData(result,err?"fail":"suc"));
            callback?callback():"";
        })
    },
    findOne : function(key,req,res,logMsg){ //根据ID查找单条记录
        var params = url.parse(req.url,true);
        console.log(req.url);
        var targetId = params.query.uid;
        if(shortid.isValid(targetId)){
            modelMap[key].findOne({_id : targetId}, function (err,result) {
                if(err){
                    res.next(err);
                }else{
                    console.log(logMsg+" success!");
                    return res.json(result);
                }
            }).populate('items').populate('items.ing');
        }else{
            res.end(settings.system_illegal_param);
        }

    },
    updateOneByID : function(key,req,res,logMsg){
        var params = url.parse(req.url,true);
        var targetId = params.query.uid;

        if(shortid.isValid(targetId)){
            var conditions = {_id : targetId};
            var update = {$set : req.body};
            modelMap[key].update(conditions, update, function (err,result) {
                if(err){
                    res.end(err);
                }else{
                    console.log(logMsg+" success!");
                    res.end("success");
                }
            })
        }else{
            res.end(settings.system_illegal_param);
        }

    },
    addOne : function(key,req,res){
        var newObj = new modelMap[key](req.body);
        newObj.save(function(err){
            console.log("模型【"+key+"】【addOne】新增"+(err?"失败":"成功"));
            res.json(DbCore.wrapData({},err?"fail":"suc"));
        });
    },

    pagination : function(key,req,res,orConditions,conditions){
        var obj=modelMap[key];
        var params = url.parse(req.url,true);
        var startNum = (params.query.currentPage - 1)*params.query.limit + 1;
        var currentPage = Number(params.query.currentPage);
        var limit = Number(params.query.limit);
        var pageInfo;
//    根据条件查询记录(如果有条件传递，则按条件查询)
        var query;
        if(orConditions && orConditions.length >= 1){
            query=obj.find(conditions).or(orConditions);
        }else if(conditions){
            query=obj.find(conditions);
        } else{
            query=obj.find({});
        }
        query.sort({'time': -1});

        if(obj == Setmeal){
            query.populate('items');
        }else if(obj == Purchase){
            query.populate('items.ing');
        }

        query.exec(function(err,docs){
            if(err){
                console.log(err)

            }else {
                var totalPrice=0;
                var pay=0;
                if(obj==Purchase||obj==Sale){
                    for(i in docs){
                        totalPrice+=docs[i].price;
                    }
                }else if(obj==CashFlow){
                    for(i in docs) {
                        if (docs[i].type == 0) {
                            totalPrice += docs[i].price;
                        } else {
                            pay += docs[i].price;
                        }
                    }
                }
                pageInfo = {
                    "totalItems" : docs.length,
                    "currentPage" : currentPage,
                    "limit" : limit,
                    "startNum" : Number(startNum)
                };
                return res.json({
                    totalPrice:totalPrice ,
                    "pay":pay,
                    docs : docs.slice(startNum - 1,startNum + limit -1),
                    "ingredienttypes":settings.INGREDIENTTYPES,
                    "cuisinetypes":settings.CUISINETYPES,
                    "cashFlowTypes":settings.CASHFLOWTYPES,
                    pageInfo : pageInfo
                });
            }
        })
    },

    getPaginationResult : function(key,req,res,q,filed){// 通用查询，带分页，注意参数传递格式,filed为指定字段
        var obj=modelMap[key];
        var searchKey = req.query.searchKey;
        var page = parseInt(req.query.page);
        var limit = parseInt(req.query.limit);
        if (!page) page = 1;
        if (!limit) limit = 15;
        var order = req.query.order;
        var sq = {}, Str, A = 'problemID', B = 'asc';
        if (order) {    //是否有排序请求
            Str = order.split('_');
            A = Str[0]; B = Str[1];
            sq[A] = B;    //关联数组增加查询条件，更加灵活，因为A是变量
        } else {
            sq.date = -1;    //默认排序查询条件
        }

        var startNum = (page - 1)*limit;
        var resultList;
        var resultNum;
        if(q && q.length > 1){ // 多条件只要其中一条符合
            resultList = obj.find().or(q,filed).sort(sq).skip(startNum).limit(limit);
            resultNum = obj.find().or(q,filed).count();
        }else{
            resultList = obj.find(q,filed).sort(sq).skip(startNum).limit(limit);
            resultNum = obj.find(q,filed).count();
        }
        //        分页参数
        var pageInfo = {
            "totalItems" : resultNum,
            "currentPage" : page,
            "limit" : limit,
            "startNum" : startNum +1,
            "searchKey" : searchKey
        };
        var datasInfo = {
            docs : resultList,
            pageInfo : pageInfo
        };

        return datasInfo;
    },

    getDatasByParam : function(key,req,res,q){// 通用查询list不带分页，注意参数传递格式,通过express-promise去掉了回调方式返回数据
        var obj=modelMap[key];
//        默认查询所有记录，有条件顺带排序和查询部分记录
        var order = req.query.order;
        var limit = parseInt(req.query.limit);
        var sq = {}, Str, A = 'problemID', B = 'asc';
        if (order) {    //是否有排序请求
            Str = order.split('_');
            A = Str[0]; B = Str[1];
            sq[A] = B;    //关联数组增加查询条件，更加灵活，因为A是变量
        } else {
            sq.date = -1;    //默认排序查询条件
        }
        if(!limit){
            return obj.find(q).sort(sq);
        }else{
            return obj.find(q).sort(sq).skip(0).limit(limit);
        }

    },

    getKeyArrByTokenId : function(tokenId){
        var newLink = DbOpt.decrypt(tokenId,settings.encrypt_key);
        var keyArr = newLink.split('$');
        return keyArr;
    },

    getCount : function(obj,req,res,conditions){ // 查询指定对象的数量
        obj.count(conditions, function (err, count) {
            if (err){
                console.log(err);
            }else{
                return res.json({
                    count : count
                });
            }

        });
    },
    encrypt : function(data,key){ // 密码加密
        var cipher = crypto.createCipher("bf",key);
        var newPsd = "";
        newPsd += cipher.update(data,"utf8","hex");
        newPsd += cipher.final("hex");
        return newPsd;
    },
    decrypt : function(data,key){ //密码解密
        var decipher = crypto.createDecipher("bf",key);
        var oldPsd = "";
        oldPsd += decipher.update(data,"hex","utf8");
        oldPsd += decipher.final("utf8");
        return oldPsd;
    }
};



module.exports = DbCore;